﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using PictbaseAirApi;

namespace PictbaseSharePointLibrary
{
    public class PictbaseActivity
    {
        //ows_ID
        public int ID { get; set; }
        //ows_Title
        public String Title { get; set; }
        //ows_Priority
        public String Priority { get; set; }
        //ows_Status
        public String Status { get; set; }
        //ows_Body
        public String Body { get; set; }
        //ows_StartDate
        public DateTime? StartDate { get; set; }
        //ows_DueDate
        public DateTime? DueDate { get; set; }
        //ows_IMEI
        public String IMEI { get; set; }
        //ows_IsSentToPictbase
        public Boolean? IsSentToPictbase { get; set; }
        //ows_Client
        public String Client { get; set; }
        //ows_Site
        public String Site { get; set; }

    }
    public partial class PictbaseDataSync
    {
        public void SyncSharePointToPictbase()
        {
            _list = ListsWS.GetList(SharePointList);

            if (_list == null)
                throw new Exception("List not found");

            PictbaseActivity[] activities = GetActivities();

            CompanyUserList users = EntityManager.CompanyUserGetList(0, int.MaxValue);
            ClientList clients = EntityManager.ClientGetList(0, int.MaxValue);

            List<int> idsToUpdate = new List<int>();


            foreach (PictbaseActivity pictbaseActivity in activities)
            {
                int? companyUserId = (from u in users where u.PinCode == pictbaseActivity.IMEI select u.id).FirstOrDefault();
                int? clientId = (from c in clients where c.Title.ToLower() == pictbaseActivity.Client.ToLower() select c.id).FirstOrDefault();

                if (companyUserId != null && clientId != null)
                {
                    int? siteid =
                        (from s in EntityManager.SiteGetList(0, int.MaxValue, clientId)
                         where s.Title.ToLower() == pictbaseActivity.Site.ToLower()
                         select s.id).FirstOrDefault();

                    if (siteid != null)
                    {
                        try
                        {
                            Task task = new Task();
                            task.companyUserId = companyUserId;
                            task.Description = pictbaseActivity.Body;
                            task.StartDate = pictbaseActivity.StartDate;
                            //task.Duration = 
                            task.Priority = "Normal";// pictbaseActivity.Priority;
                            task.structureId = PictbaseStructureId;

                            task.siteId = siteid;

                            // Must be moved to the end 
                            idsToUpdate.Add(pictbaseActivity.ID);

                            EntityManager.TaskInsert(task);

                            
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception.Message);
                        }
                        
                    }
                }
            }

            if(idsToUpdate.Count > 0)
            {
                Console.Write("Update SharePoint List");

                // Update SharePoint List

                /*Create an XmlDocument object and construct a Batch element and its
                 attributes. Note that an empty ViewName parameter causes the method to use the default view. */
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
                batchElement.SetAttribute("OnError", "Continue");
                batchElement.SetAttribute("ListVersion", _list.Attributes["Version"].Value);
                //batchElement.SetAttribute("ViewName", "{876D8F87-8DEA-4E2A-887C-4F3E58B2DFAC}");

                /*Specify methods for the batch post using CAML. To update or delete, 
                specify the ID of the item, and to update or add, specify 
                the value to place in the specified column.*/



                int index = 1;
                batchElement.InnerXml = String.Concat(
                    (from i in idsToUpdate
                     select
                         String.Format(
                             @"<Method ID='{0}' Cmd='Update'><Field Name='ID'>{1}</Field><Field Name='IsSentToPictbase'>TRUE</Field></Method>",
                             index++, i)).ToArray());

                /*Update list items. This example uses the list GUID, which is recommended, 
                 but the list display name will also work.*/
                try
                {
                    var res = ListsWS.UpdateListItems(_list.Attributes["ID"].Value, batchElement);
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                }
            }
        }

        private PictbaseActivity[] GetActivities()
        {
            XmlDocument xmlDoc = new System.Xml.XmlDocument();

            XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
            XmlNode ndViewFields =
                xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
            XmlNode ndQueryOptions =
                xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

            ndQueryOptions.InnerXml =
                "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc>";
            //ndViewFields.InnerXml = @"<FieldRef Name='ID' /><FieldRef Name='ows_Title'/><FieldRef Name='Priority'/><FieldRef Name='TaskStatus'/><FieldRef Name='PercentComplete'/><FieldRef Name='AssignedTo'/><FieldRef Name='Body'/><FieldRef Name='StartDate'/><FieldRef Name='TaskDueDate'/><FieldRef Name='IMEI'/><FieldRef Name='IsSentToPictbase'/>";

            ndQuery.InnerXml =
@"<Where>
    <Eq>
        <FieldRef Name='IsSentToPictbase' />
        <Value Type='Boolean'>True</Value>
    </Eq>
</Where>";
            XmlNode ndListItems = null;
            try
            {
                ndListItems =
                    ListsWS.GetListItems(_list.Attributes["ID"].Value, null, ndQuery,
                    ndViewFields, null, ndQueryOptions, null);
            }

            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Console.Write("Message:\n" + ex.Message + "\nDetail:\n" +
                    ex.Detail.InnerText +
                     "\nStackTrace:\n" + ex.StackTrace);
                return new PictbaseActivity[] { };
            }


            XmlNode xmlItems =
                (from x in ndListItems.ChildNodes.Cast<XmlNode>() where x.Name == "rs:data" select x).FirstOrDefault();

            List<PictbaseActivity> activities = new List<PictbaseActivity>();

            foreach (XmlNode xmlNode in xmlItems.ChildNodes.Cast<XmlNode>())
            {
                if (xmlNode.Name != "z:row")
                    continue;

                activities.Add(
                    new PictbaseActivity()
                        {
                            //ows_Title
                            Title = xmlNode.Attributes["ows_Title"] != null ? xmlNode.Attributes["ows_Title"].Value : "",
                            //ows_Body
                            Body = xmlNode.Attributes["ows_Body"] != null ? xmlNode.Attributes["ows_Body"].Value : "",
                            //ows_DueDate
                            DueDate = xmlNode.Attributes["ows_DueDate"] != null ? Convert.ToDateTime(xmlNode.Attributes["ows_DueDate"].Value) : (DateTime?)null,
                            //ows_ID
                            ID = xmlNode.Attributes["ows_ID"] != null ? Convert.ToInt32(xmlNode.Attributes["ows_ID"].Value) : -1,
                            //ows_IMEI
                            IMEI = xmlNode.Attributes["ows_IMEI"] != null ? xmlNode.Attributes["ows_IMEI"].Value : "",
                            //ows_IsSentToPictbase
                            IsSentToPictbase = xmlNode.Attributes["ows_IsSentToPictbase"] != null ? xmlNode.Attributes["ows_IsSentToPictbase"].Value == "1" : false,
                            //ows_Priority
                            Priority = xmlNode.Attributes["ows_Priority"] != null ? xmlNode.Attributes["ows_Priority"].Value : "",
                            //ows_StartDate
                            StartDate = xmlNode.Attributes["ows_StartDate"] != null ? Convert.ToDateTime(xmlNode.Attributes["ows_StartDate"].Value) : (DateTime?)null,
                            //ows_Status
                            Status = xmlNode.Attributes["ows_Status"] != null ? xmlNode.Attributes["ows_Status"].Value : "",
                            //ows_Status
                            Client = xmlNode.Attributes["ows_Client"] != null ? xmlNode.Attributes["ows_Client"].Value : "",
                            //ows_Status
                            Site = xmlNode.Attributes["ows_Site"] != null ? xmlNode.Attributes["ows_Site"].Value : "",

                        }
                    );
            }

            return activities.ToArray();
        }
    }
}
